const jwt = require('jsonwebtoken');
const User = require('../models/User');

const register = async (req, res) => {
  try {
    const { username, email, password } = req.body;
    console.log('注册请求:', { username, email });

    // 检查用户是否已存在
    const existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      console.log('用户已存在:', email);
      return res.status(400).json({ message: '邮箱已被注册' });
    }

    // 创建新用户
    const user = await User.create({
      username,
      email,
      password
    });
    console.log('用户创建成功:', user.id);

    // 生成 token
    const token = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.status(201).json({
      message: '注册成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ 
      message: '注册失败', 
      error: error.message,
      stack: error.stack 
    });
  }
};

const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    console.log('登录请求:', { email });
    
    // 查找用户
    const user = await User.findOne({ where: { email } });
    if (!user) {
      console.log('用户不存在:', email);
      return res.status(401).json({ message: '邮箱或密码错误' });
    }

    // 验证密码
    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      console.log('密码错误:', email);
      return res.status(401).json({ message: '邮箱或密码错误' });
    }

    // 生成 token
    const token = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ 
      message: '登录失败', 
      error: error.message,
      stack: error.stack 
    });
  }
};

const getCurrentUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id, {
      attributes: { exclude: ['password'] }
    });
    res.json(user);
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ 
      message: '获取用户信息失败', 
      error: error.message,
      stack: error.stack 
    });
  }
};

module.exports = {
  register,
  login,
  getCurrentUser
}; 